<?php

namespace app\common\model;

use think\Exception;
use think\Model;

class Base extends Model
{

    public function add($data = [], $auto_time = true)
    {
        try {
            unset($data['token']);
            unset($data['id']);
            if ($auto_time) {
                $current = time();
                if (isset($this->createTime) && $this->createTime) {
                    $data['createtime'] = $current;
                }
                if (isset($this->updateTime) && $this->updateTime) {
                    $data['updatetime'] = $current;
                }
            }
            $this->allowField(true)->data($data, true)->isUpdate(false)->save($data);
            return Tools::returnArray(1, '', ['id' => $this->max('id')]);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    public function fetch($where = [], $field = '*', $sort = [])
    {
        try {
            if ($sort) {
                $data = $this->where($where)->order($sort)->field($field)->find();
            } else {
                $data = $this->where($where)->field($field)->find();
            }

            return Tools::returnArray(1, '', $data ?? []);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    public function fetchOne($where = [], $field = '*')
    {
        try {
            $data = $this->where($where)->field($field)->order('id desc')->find();
            return Tools::returnArray(1, '', $data);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }


    public function edit($where = [], $data = [])
    {
        try {
            unset($data['token']);
            unset($data['id']);
            if (isset($this->updateTime) && $this->updateTime) {
                $data['updatetime'] = time();
            }
            $this->allowField(true)->isUpdate(false)->save($data, $where);
            return Tools::returnArray(1);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    public function selectAll($where = [], $field = '*', $sort = false, $order = [])
    {
        try {
            $return = [];
            if ($order) {
                $list = $this->where($where)->field($field)->order($order)->select();
            } else {
                $list = $this->where($where)->field($field)->select();
            }
            if ($sort && $list) {
                foreach ($list as $item) {
                    $return[$item['id']] = $item;
                }
            } else {
                $return = $list;
            }
            return Tools::returnArray(1, '', $return);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    public function selectKeyValue($where, $key, $value, $first = '', $return_id = false)
    {
        $return = [];
        if ($first) {
            $return[0] = $first;
        }
        $list = $this->where($where)->field("$key,$value")->select();
        if ($list) {
            foreach ($list as $item) {
                $return[$item[$key]] = $return_id ? $item[$value] . '(id:' . $item[$key] . ')' : $item[$value];
            }
        }
        return $return;
    }

    public function drop($where = [])
    {
        try {
            $this->update(['deletetime' => time()], $where);
            return Tools::returnArray(1);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }


    public function existOne($where = [])
    {
        return $this->where($where)->value('id') > 0 ? 1 : 0;
    }

    public function whereCount($where = [], $field = 'id')
    {
        return $this->where($where)->count($field);
    }

    public function whereSum($wehre, $field = '')
    {
        return $this->where($wehre)->sum($field);
    }

    public function fetchIn($ids = '', $field = '*', $column = 'id', $limit = 0, $order = [], $where = [])
    {
        if (empty($ids)) {
            return [];
        }
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        if ($limit > 0) {
            return $this->whereIn($column, $ids)->where($where)->limit($limit)->field($field)->order($order)->select();
        } else {
            try {
                return $this->whereIn($column, $ids)->where($where)->field($field)->order($order)->select();
            } catch (Exception $e) {
                return [];
            }
        }
    }

    public function setIncrease($where = [], $field = '', $step = 1)
    {
        try {
            $this->where($where)->setInc($field, $step);
            return Tools::returnArray(1);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    public function setDecrease($where = [], $field = '', $step = 1)
    {
        try {
            $this->where($where)->setDec($field, $step);
            return Tools::returnArray(1);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    public function fetchValue($where = [], $field = 'id', $sort = [])
    {
        $value = $this->where($where)->order($sort)->value($field);
        return $value ?? '';
    }

    public function realDrop($where)
    {
        try {
            $this->where($where)->delete();
            return Tools::returnArray(1);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    public function arrayToStr($list = [], $fields = 'id', $to_str = false)
    {
        $arr = [];
        if (empty($list)) {
            return '';
        }
        $fields = explode(',', $fields);
        $filed_count = count($fields);

        foreach ($list as $item) {
            $temp = '';
            foreach ($fields as $index => $field) {
                if ($index + 1 < $filed_count) {
                    $temp .= $item[$field] . '-';
                } else {
                    $temp .= $item[$field];
                }
            }
            $arr[] = $temp;
        }
        return $to_str ? implode(',', $arr) : $arr;
    }

    /**
     * 功能：获取$field字段的数组
     * @param $where array 查询条件
     * @param $field string 获取的字段
     * @param $order array 排序
     * @return array {code:1,msg:'',data:'',url:''}
     */
    public function selectArray($where = [], $field = '', $order = [])
    {
        if (empty($field)) return [];
        try {
            $return = [];
            if ($order) {
                $list = $this->where($where)->field($field)->order($order)->select();
            } else {
                $list = $this->where($where)->field($field)->select();
            }
            if ($list) {
                foreach ($list as $item) {
                    $return[$item[$field]] = $item[$field];
                }
                $return = array_values($return);
            }

            return Tools::returnArray(1, '', $return);
        } catch (Exception $e) {
            return Tools::returnArray(0, $e->getMessage());
        }
    }

    protected function jsonDecodeValue($value)
    {
        return is_string($value) ? json_decode($value, true) : $value;
    }

    protected function jsonEncodeValue($value)
    {
        return is_array($value) ? json_encode($value, 320) : $value;
    }

}